package com.itany.mybatis.util;

import com.itany.mybatis.Test01;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * Description: MyBatisUtil
 * Author: liudaolin@itany.com
 * Date: 2021/07/20 11:48
 * Version: 1.0 版本信息
 */
public class  MyBatisUtil {

    private static SqlSessionFactory factory;
    private static ThreadLocal<SqlSession> local;

    static {
        local = new ThreadLocal<SqlSession>();
        try {
            // 1.创建 SqlSessionFactory 构建器
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            // 2.加载 mybatis-config 文件, 创建 SqlSessionFactory
            factory = builder.build(MyBatisUtil.class
                    .getClassLoader()
                    .getResourceAsStream("mybatis-config.xml"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("MyBatisUtil初始化失败");
        }
    }

    /**
     * 获取 SqlSession
     * @return
     */
    public static SqlSession getSession() {
        SqlSession session = local.get();
        if(null == session){
            session = factory.openSession();
            local.set(session);
        }
        return session;
    }

    /**
     * 关闭 SqlSession
     */
    public static void close() {
        SqlSession session = local.get();
        if(null != session){
            // 移除当前的 session
            local.remove();
            // 再关闭 当前的 session
            session.close();
        }
    }

}
